服务配置 cors 跨域

微服务版本: 网关跨域支持

参考资料

如果不知道什么是跨域(CORS),建议先阅读以下内容:

方式一. 图形化开启跨域

版本支持

v5.6 后版本支持,通过路由管理模块开启指定服务的跨域访问。

图形化开启跨域

方式二. 配置文件开启跨域

在 nacos pigx-gateway-dev.yml 增加如下配置:

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          "[/**]":
            allowedOriginPatterns: "*"
            allowed-methods: "*"
            allowed-headers: "*"
            allow-credentials: true
            exposedHeaders: "Content-Disposition,Content-Type,Cache-Control"
环境配置建议

以上配置可作为开发环境使用,生产环境建议根据实际情况修改(请先理解 CORS,并参考 org.springframework.cloud.gateway.config.GlobalCorsProperties)。跨域时会产生预检请求(Pre-Flight Request),这样就会对你的服务器产生额外的网络请求。如果可以通过部署手段解决跨域,则可以关闭跨域支持,方法是把以上配置信息清理掉。

单体项目配置跨域

V5.11+ 版本

  • pigx-boot/application.yml
security.cors.enabled: true

低版本手动添加如下代码

认证服务器设置允许跨域:pigx-auth/AuthorizationServerConfiguration

认证服务器跨域配置

资源服务器设置允许跨域:common-security/PigxResourceServerConfiguration

资源服务器跨域配置
.cors(cors -> cors.configurationSource(request -> {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration corsConfiguration = new CorsConfiguration();
    corsConfiguration.addAllowedOriginPattern("*");
    corsConfiguration.addAllowedHeader("*");
    corsConfiguration.addAllowedMethod("*");
    corsConfiguration.setAllowCredentials(true);
    source.registerCorsConfiguration("/**", corsConfiguration);
    return corsConfiguration;
}))
        ...